import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { actionCreators } from './store'
import Topic from './base/Topic'
import List from './base/List'
import Recommend from './base/Recommend'
import Writer from './base/Writer'

import {
  HomeWrapper,
  HomeLeft,
  HomeRight,
  BackTop
} from './style'

class Home extends PureComponent {
  componentDidMount () {
    this.props.getHomeData()
    this.bindScrool()
  }

  componentWillUnmount () {
    window.removeEventListener('scroll', this.props.changeBackTop)
  }

  render () {
    const { showBackTop } = this.props

    return (
      <HomeWrapper>
        <HomeLeft>
          <img 
            className='banner-img' 
            src="//upload.jianshu.io/admin_banners/web_images/4318/60781ff21df1d1b03f5f8459e4a1983c009175a5.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540" 
            alt=''
          />
          <Topic />
          <List />
        </HomeLeft>
        <HomeRight>
          <Recommend />
          <Writer />
        </HomeRight>
        {showBackTop ? <BackTop onClick={this.backTop}>顶部</BackTop> : null}
      </HomeWrapper>
    )
  }

  backTop () {
    window.scrollTo(0, 0)
  }

  bindScrool () {
    window.addEventListener('scroll', this.props.changeBackTop)
  }

}

const mapState = (state) => ({
  showBackTop: state.getIn(['home', 'showBackTop'])
})

const mapAction = (dispatch) => ({
  getHomeData: () => {
    dispatch(actionCreators.getHomeDataAction())
  },

  changeBackTop: () => {
    if (document.documentElement.scrollTop > 100) {
      dispatch(actionCreators.changeBackTopAction(true))
    } else {
      dispatch(actionCreators.changeBackTopAction(false))
    }
  }
})

export default connect(mapState, mapAction)(Home)
